package com.toolconclusion.transition;

import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: Sun
 * @DateTime: 2025/4/1 10:53
 * @Description: 实体和dto转换工具
 **/
public class EntityConverter {
    public static <E, D> D entity2DTO(E entity, Class<D> dtoClass) {
        return convertBean(entity, dtoClass);
    }

    private static <B1, B2> B2 convertBean(B1 b1, Class<B2> b2Class) {
        B2 b2 = null;
        if (b1 == null) {
            return null;
        }
        try {
            b2 = b2Class.newInstance();
            BeanUtils.copyProperties(b1, b2);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return b2;
    }

    public static <E, D> List<D> entity2DTO(List<E> entityList, Class<D> dtoClass) {
        Stream<E> stream = entityList.stream();

        return stream.map(e->entity2DTO(e,dtoClass)).collect(Collectors.toList());
    }

}
